package com.springboot.common.lock.impl;

import com.springboot.common.lock.AbstractLock;
import java.util.concurrent.TimeUnit;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;

/**
 * zk分布式锁
 *
 * @author supu
 * @date 2019-03-22 11:29
 **/
public class SimpleZookeeperLock extends AbstractLock {

    private final InterProcessMutex mutex;

    public SimpleZookeeperLock(String path, CuratorFramework curatorFramework) {
        super(path);
        this.mutex = new InterProcessMutex(curatorFramework, super.path);
    }

    @Override
    public void lock() throws Exception {
        mutex.acquire();
    }

    @Override
    public boolean tryLock(long time, TimeUnit timeUnit) throws Exception {
        return mutex.acquire(time, timeUnit);
    }

    @Override
    public void unLock() throws Exception {
        if (mutex.isAcquiredInThisProcess()) {
            mutex.release();
        }
    }
}
